import { Modal, List, Button, Typography, Input, Row, Col, Form } from "antd";
import { PlusOutlined } from "@ant-design/icons";

import "./index.scss";

const { ipcRenderer, remote } = window.electron;
const { users: initialUsers = [] } = remote.getGlobal("config");

export default class Users extends React.PureComponent {
  state = {
    visible: false,
    users: initialUsers,
    editRow: {}
  };

  componentDidMount() {
    ipcRenderer.on("showUsers", () => {
      this.setState({ visible: true });
    });
  }

  userForm = {};

  addEditableUser = () => {
    const { users } = this.state;
    const _id = Math.random() + "";
    users.push({
      editable: true,
      _id
    });
    this.userForm[_id] = React.createRef();
    this.setState({ users: [...users] });
  };

  saveUserConfig = () => {
    const { users } = this.state;
    ipcRenderer.send("setConfig", {
      users: users.filter(user => !user.editable)
    });
    this.setState({ visible: false });
  };

  removeUser = (index, _id) => {
    const { users } = this.state;
    users.splice(index, 1);
    delete this.userForm[_id];
    this.setState({ users: [...users] });
  };

  saveAddUser = (values, index) => {
    const { users } = this.state;
    users[index] = values;
    this.setState({ users: [...users] });
  };

  changeUserName = (value, index) => {
    if (!value.trim()) {
      return;
    }
    const { users } = this.state;
    users[index].name = value;
    this.setState({ users: [...users] });
  };

  onValuesChange(index, allValues) {
    let { users } = this.state;
    users[index] = { ...users[index], ...allValues };
    this.setState({
      users: [...users]
    });
  }

  getFooter = () => {
    return (
      <Row>
        <Col>
          <Button
            type="primary"
            className="mr-3"
            onClick={this.addEditableUser}
          >
            <PlusOutlined />
            添加
          </Button>
        </Col>
        <Col flex={1}>
          <Button onClick={() => this.setState({ visible: false })}>
            取消
          </Button>
          <Button type="primary" onClick={this.saveUserConfig}>
            确定
          </Button>
        </Col>
      </Row>
    );
  };

  renderItem = (item, index) => {
    const actions = [
      <Button
        key="list-delete"
        type="link"
        size="small"
        danger
        onClick={() => this.removeUser(index, item._id)}
      >
        删除
      </Button>
    ];
    if (item.editable) {
      actions.unshift(
        <Button
          key="list-add"
          type="link"
          size="small"
          onClick={() => this.userForm[item._id].current.submit()}
        >
          添加
        </Button>
      );
    }
    return (
      <List.Item actions={actions}>
        {item.editable ? (
          <Form
            layout="inline"
            key={item._id}
            ref={this.userForm[item._id]}
            initialValues={item}
            onValuesChange={(changedValues, allValues) =>
              this.onValuesChange(index, allValues)
            }
            onFinish={values => this.saveAddUser(values, index)}
          >
            <Form.Item
              name="uid"
              rules={[
                { required: true, message: "请输入用户uid" },
                {
                  validator: (rule, value) => {
                    if (/^\d{16}(\d{2})?$/.test(value)) {
                      return Promise.resolve();
                    }
                    return Promise.reject("uid必须是16位或18位数字");
                  }
                },
                {
                  validator: (rule, value) => {
                    if (
                      value &&
                      this.state.users.some(
                        user => user._id != item._id && user.uid == value
                      )
                    ) {
                      return Promise.reject("已存在该uid用户的备注");
                    }
                    return Promise.resolve();
                  }
                }
              ]}
            >
              <Input placeholder="请输入用户uid" />
            </Form.Item>
            <Form.Item
              name="name"
              rules={[{ required: true, message: "请输入用户的备注名称" }]}
            >
              <Input placeholder="请输入用户名称备注" />
            </Form.Item>
          </Form>
        ) : (
          <Row className="flex-full">
            <Col span={12}>{item.uid}</Col>
            <Col span={12}>
              <Typography.Text
                editable={{
                  onChange: value => this.changeUserName(value, index)
                }}
              >
                {item.name}
              </Typography.Text>
            </Col>
          </Row>
        )}
      </List.Item>
    );
  };

  render() {
    const { visible, users } = this.state;

    return (
      <Modal
        centered
        closable={false}
        maskClosable={false}
        visible={visible}
        title="用户备注设置"
        footer={this.getFooter()}
      >
        {users.length > 0 && (
          <Row style={{ marginRight: 60 }}>
            <Col span={12}>
              <b>uid</b>
            </Col>
            <Col span={12}>
              <b>备注</b>
            </Col>
          </Row>
        )}
        <List dataSource={users} renderItem={this.renderItem} />
      </Modal>
    );
  }
}
